<?php

namespace app\api\controller;

use app\api\service\ProductService;
use app\common\controller\ApiBase;
use app\common\model\Product as ProductModel;
use think\Db;
use think\Exception;

class Product extends ApiBase
{

    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];


    public function list()
    {
        $this->checkRequestParam(\app\common\validate\Product::class);
        $param = $this->request->param();
        $where = [];
        $alias = 'product';
        if ($this->request->has('category_id')) {
            $where = [$alias . '.category_id' => $param['category_id']];
        }


        $product = ProductModel::alias($alias)->where($where)
            ->with([
                'category' => function ($query) {
                    $query->withField(['id', 'pid', 'type', 'name', 'nickname', 'flag', 'status']);
                },
                'fbx' => function ($query) {
                    $query->withField(['id', 'name', 'file', 'file_name', 'images', 'images_name', 'proportion',]);
                },
            ])
            ->paginate($this->getPaginate());

        $data = $product->items();
        $count = $product->total();

        return $this->success('成功', ['count' => $count, 'list' => $data]);
    }

    public function submitOrder()
    {
        $this->checkRequestParam(\app\common\validate\Product::class);
        $param = $this->request->param();
        $product = ProductModel::where(['id' => $param['product_id'], 'status' => 1])->find();
        if (empty($product)) {
            $this->error('找不到相关的商品信息');
        }

        $service = new ProductService();
        Db::startTrans();
        try {
            $order = $service->submitOrder($product, $param['qty'], $this->auth->id);
            if (empty($order)) {
                Db::rollback();
                $this->error($service->getMsg());
            }
            Db::commit();
            $this->success('成功', ['order' => $order]);

        }catch (Exception $e) {
            Db::rollback();
            $this->errorTrace('提交商品订单失败。',$e);
        }

    }
}
